/*
* @Date: 2021/2/23
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import Router from 'koa-router';
import fs from 'fs';
import config from '../config';
import utils from '../utils';
import path from 'path';

export default function upload(app) {
  let router = Router(app);
  router.post('/upload', async (ctx, next) => {
    const file = ctx.request.files.file;
    const reader = fs.createReadStream(file.path);
    const filePath = config.upload.path + utils.formatDate(new Date(), 'yyyyMMdd') + `/${utils.getGuid()}.${file.name.substr(file.name.lastIndexOf('.'))}`;
    const absolutePath = path.resolve(`../../${filePath}`);
    const upStream = fs.createWriteStream(absolutePath);
    reader.pipe(upStream);
    return ctx.body = JSON.stringify({
      code: 0,
      message: '上传成功',
      data: {
        path: filePath,
      },
    });
  });
  router.post('/uploadfiles', async (ctx,next) => {
    const files = ctx.request.files.file;
    const paths = [];
    for (let file of files) {
      const reader = fs.createReadStream(file.path);
      const filePath = config.upload.path + utils.formatDate(new Date(), 'yyyyMMdd') + `/${utils.getGuid()}.${file.name.substr(file.name.lastIndexOf('.'))}`;
      const absolutePath = path.resolve(`../../${filePath}`);
      const upStream = fs.createWriteStream(absolutePath);
      reader.pipe(upStream);
      paths.push(filePath);
    }
    return ctx.body = {
      code: 0,
      message: '上传成功',
      data: paths,
    };
  });
}
